package com.niit.blog.controller;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.niit.blog.config.ConstConfiguration;
import com.niit.blog.util.BlogUtils;
import com.niit.blog.util.Result;

/**
 * @Title: UploadFileController.java
 * @Description: 上传文件控制器
 */
@Controller
@RequestMapping("/user")
public class UploadFileController {
	
	@Autowired
    private ConstConfiguration constConfig;

	/**
	 * @Description: 上传文件
	 * @param httpServletRequest
	 * @param file
	 * @return
	 * @throws URISyntaxException Result
	 */
//    @PostMapping({"/upload/file"})
//    @ResponseBody
//    public Result upload(HttpServletRequest httpServletRequest, @RequestParam("file") MultipartFile file) throws URISyntaxException {
//        String fileName = file.getOriginalFilename();
//        String suffixName = fileName.substring(fileName.lastIndexOf("."));
//        //生成文件名称通用方法
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
//        Random r = new Random();
//        StringBuilder tempName = new StringBuilder();
//        tempName.append(sdf.format(new Date())).append(r.nextInt(100)).append(suffixName);
//        String newFileName = tempName.toString();
//        File fileDirectory = new File(constConfig.getUploadPath());
//        //创建文件
//        File destFile = new File(constConfig.getUploadPath() + newFileName);
//        try {
//            if (!fileDirectory.exists()) {
//                if (!fileDirectory.mkdir()) {
//                    throw new IOException("文件夹创建失败,路径为：" + fileDirectory);
//                }
//            }
//            file.transferTo(destFile);
//            Result resultSuccess = ResultGenerator.genSuccessResult();
//            resultSuccess.setData(BlogUtils.getHost(new URI(httpServletRequest.getRequestURL() + "")) + "/upload/" + newFileName);
//            return resultSuccess;
//        } catch (IOException e) {
//            e.printStackTrace();
//            return ResultGenerator.genFailResult("文件上传失败");
//        }
//    }

}
